<template>
  <div class="recommendations">
    <!-- 标题 -->
    <div class="feedback-main-title">请选择你认为最准确的推荐算法</div>
    <!-- 用户反馈功能 -->
    <div class="feedback-bar card-select-bar left-align-bar">
      <div class="algo-card-group">
        <div
          v-for="algo in algorithmOptions"
          :key="algo.value"
          class="algo-card"
          :style="{ background: algo.bg }"
          @click="submitFeedback(algo.value)"
        >
          <v-icon large class="algo-icon">{{ algo.icon }}</v-icon>
          <div class="algo-label">{{ algo.label }}</div>
        </div>
      </div>
    </div>

    <!-- 添加算法选择统计图表 -->
    <div class="stats-section">
      <div class="white--text font-weight-bold text-h6 d-flex justify-start my-4">
        用户算法偏好分布
      </div>
      <div class="chart-container" ref="chartContainer"></div>
    </div>

    <div class="white--text font-weight-bold text-h5 d-flex justify-start my-6">
      基于物品的协同过滤算法推荐电影
    </div>
    <v-row>
      <v-col 
        cols="12" lg="2.4" md="4" sm="6" xs="12"
        v-for="(item, index) in recs" 
        :key="index"
        class="movie-col"
      >
        <movie-card :movie="item"/>
      </v-col>
    </v-row>

    <div class="white--text font-weight-bold text-h5 d-flex justify-start my-6">
      基于用户的协同过滤算法推荐电影
    </div>
    <v-row>
      <v-col 
        cols="12" lg="2.4" md="4" sm="6" xs="12"
        v-for="(item, index) in recs2" 
        :key="index"
        class="movie-col"
      >
        <movie-card :movie="item"/>
      </v-col>
    </v-row>

    <div class="white--text font-weight-bold text-h5 d-flex justify-start my-6">
      基于GraphX的推荐算法推荐电影
    </div>
    <v-row>
      <v-col 
        cols="12" lg="2.4" md="4" sm="6" xs="12"
        v-for="(item, index) in graphXRecs.slice(0, 5)" 
        :key="'graphx-'+index"
        class="movie-col"
      >
        <movie-card :movie="item"/>
      </v-col>
    </v-row>

    <div class="white--text font-weight-bold text-h5 d-flex justify-start my-6">
      基于矩阵分解的推荐算法推荐电影
    </div>
    <v-row>
      <v-col 
        cols="12" lg="2.4" md="4" sm="6" xs="12"
        v-for="(item, index) in mfRecs.slice(0, 5)" 
        :key="'mf-'+index"
        class="movie-col"
      >
        <movie-card :movie="item"/>
      </v-col>
    </v-row>
  </div>
</template>

<script>
import MovieCard from "@/components/MovieCard";
import {getItemCF, getUserCF, getGraphXRec, getMFRec, saveFeedback, getAlgorithmStats} from "@/api/movie";
import {mapState} from 'vuex'
import * as echarts from 'echarts'

export default {
  name: "Recommendations",
  components: { MovieCard },
  data: () => ({
    recs: [],
    recs2: [],
    graphXRecs: [],
    mfRecs: [],
    algorithmOptions: [
      { label: '物品协同过滤', value: 'ItemCF', icon: 'mdi-cube-scan', bg: 'linear-gradient(135deg, #42a5f5 0%, #478ed1 100%)' },
      { label: '用户协同过滤', value: 'UserCF', icon: 'mdi-account-group', bg: 'linear-gradient(135deg, #66bb6a 0%, #43a047 100%)' },
      { label: 'GraphX', value: 'GraphX', icon: 'mdi-graph', bg: 'linear-gradient(135deg, #ffa726 0%, #fb8c00 100%)' },
      { label: '矩阵分解', value: 'MF', icon: 'mdi-table-large', bg: 'linear-gradient(135deg, #ab47bc 0%, #8e24aa 100%)' }
    ],
    chart: null
  }),
  computed: {
    ...mapState(['uid'])
  },
  methods: {
    async submitFeedback(algorithm) {
      try {
        await saveFeedback({
          user_id: this.uid,
          algorithm,
          feedback_type: '算法反馈'
        });
        this.$toast ? this.$toast('反馈已提交') : alert('反馈已提交');
        // 更新统计图表
        this.updateChartData();
      } catch (error) {
        console.error('提交反馈失败:', error);
        this.$toast ? this.$toast('提交失败，请重试') : alert('提交失败，请重试');
      }
    },
    initChart() {
      if (this.chart) {
        this.chart.dispose();
      }
      this.chart = echarts.init(this.$refs.chartContainer);
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ['物品协同过滤', '用户协同过滤', 'GraphX', '矩阵分解'],
          axisLabel: {
            color: '#fff'
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            color: '#fff'
          }
        },
        series: [{
          name: '选择人数',
          type: 'bar',
          data: [0, 0, 0, 0],
          itemStyle: {
            color: function(params) {
              const colors = ['#42a5f5', '#66bb6a', '#ffa726', '#ab47bc'];
              return colors[params.dataIndex];
            }
          },
          label: {
            show: true,
            position: 'top',
            color: '#fff'
          },
          barWidth: '40%'
        }]
      };
      
      this.chart.setOption(option);
      window.addEventListener('resize', this.handleResize);
    },
    handleResize() {
      if (this.chart) {
        this.chart.resize();
      }
    },
    async updateChartData() {
      try {
        const response = await getAlgorithmStats();
        if (response && response.data && response.data.data) {
          const stats = response.data.data;
          const newData = [
            stats.ItemCF || 0,
            stats.UserCF || 0,
            stats.GraphX || 0,
            stats.MF || 0
          ];
          this.chart.setOption({
            series: [{
              data: newData
            }]
          });
        }
      } catch (error) {
        console.error('获取统计数据失败:', error);
      }
    }
  },
  async mounted() {
    console.log('当前登录uid:' + this.uid);
    await getItemCF(this.uid).then(res => {
      this.recs2 = res.data.data.datas;
    });
    await getUserCF(this.uid).then(res => {
      this.recs = res.data.data.datas;
    });
    await getGraphXRec(this.uid).then(res => {
      this.graphXRecs = res.data.data.datas;
    });
    await getMFRec(this.uid).then(res => {
      this.mfRecs = res.data.data.datas;
    });
    
    // 初始化图表
    this.$nextTick(() => {
      this.initChart();
      this.updateChartData();
    });
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    if (this.chart) {
      this.chart.dispose();
      this.chart = null;
    }
  }
}
</script>

<style scoped>
.recommendations {
  padding-bottom: 40px;
}
.feedback-main-title {
  color: #fff;
  font-size: 1.5rem;
  font-weight: bold;
  margin-bottom: 18px;
  margin-top: 8px;
  text-align: left;
  letter-spacing: 1px;
}
.card-select-bar {
  display: flex;
  align-items: flex-start;
  flex-wrap: wrap;
  margin-bottom: 32px;
}
.left-align-bar {
  justify-content: flex-start;
}
.algo-card-group {
  display: flex;
  gap: 24px;
}
.algo-card {
  min-width: 140px;
  min-height: 110px;
  border-radius: 16px;
  color: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 16px rgba(0,0,0,0.18);
  cursor: pointer;
  transition: transform 0.18s, box-shadow 0.18s;
  font-size: 18px;
  font-weight: 500;
  position: relative;
}
.algo-card:hover {
  transform: translateY(-6px) scale(1.06);
  box-shadow: 0 8px 32px rgba(0,0,0,0.28);
  z-index: 2;
}
.algo-icon {
  font-size: 38px !important;
  margin-bottom: 8px;
}
.algo-label {
  font-size: 17px;
  letter-spacing: 1px;
  margin-top: 2px;
}
@media (max-width: 800px) {
  .algo-card-group {
    gap: 12px;
  }
  .algo-card {
    min-width: 100px;
    min-height: 80px;
    font-size: 15px;
  }
  .algo-label {
    font-size: 14px;
  }
  .feedback-main-title {
    font-size: 1.2rem;
  }
}
/* 在大屏幕上强制每行显示5个 */
@media (min-width: 1264px) {
  .movie-col {
    flex: 0 0 20% !important;
    max-width: 20% !important;
  }
}

.stats-section {
  margin-top: 32px;
  margin-bottom: 40px;
}

.chart-container {
  width: 100%;
  height: 400px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 12px;
  padding: 20px;
}
</style> 